#include "includes.h"

extern struct global_history history;
extern int state;
extern struct msg_view_change vc_list;
extern struct msg_prepare_ok prep_ok_list;
extern struct msg_client_update update_queue;
extern struct msg_client_update pending_updates;
extern struct client_ts last_executed;
extern struct client_ts last_enqueued;
extern struct msg_prepare *prep;
extern int host_count;
extern int local_aru;
extern int my_id;
extern int last_attempted;
extern int last_installed;
extern int last_proposed;
extern char* local_hostname;

void sync(){

	
	//DEBUGPRINT("STAGE 1\n",NULL);

	FILE *sf, *gh; 
	char* sf_path = (char*) malloc(strlen(local_hostname) + sizeof(char)*10);
	char* gh_path = (char*) malloc(strlen(local_hostname) + sizeof(char)*7);
	
	bzero((char*)sf_path, strlen(local_hostname) + sizeof(char)*10);
	bzero((char*)gh_path, strlen(local_hostname) + sizeof(char)*7);
	
	sprintf(sf_path,"%s.%s.bak",local_hostname,"state");
	sprintf(gh_path,"%s.%s.bak",local_hostname,"gh");
	
	sf = fopen(sf_path,"w+");
	gh = fopen(gh_path,"w+");
	
	//DEBUGPRINT("STAGE 2\n",NULL);
	fprintf(sf,"%d,%d,%d,%d\n",state,last_installed,last_attempted,local_aru);
	fclose(sf);
	//DEBUGPRINT("STAGE 3\n",NULL);
	struct list_head *pos;
	struct global_history *hist;
	list_for_each(pos, &history.list){
		hist = list_entry(pos, struct global_history, list);
		char* hist_str = serialize_gh(hist);
		fprintf(gh, "%s\n", hist_str);
	}
	fclose(gh);
}

void restore(){
	
	FILE *sf, *gh; 
	char* sf_path = (char*) malloc(strlen(local_hostname) + sizeof(char)*10);
	char* gh_path = (char*) malloc(strlen(local_hostname) + sizeof(char)*7);
	
	bzero((char*)sf_path, strlen(local_hostname) + sizeof(char)*10);
	bzero((char*)gh_path, strlen(local_hostname) + sizeof(char)*7);
	
	sprintf(sf_path,"%s.%s.bak",local_hostname,"state");
	sprintf(gh_path,"%s.%s.bak",local_hostname,"gh");
	
	//fprintf(stderr,"SF: %s, GH: %s\n",sf_path,gh_path);
	
	sf = fopen(sf_path,"r");
	gh = fopen(gh_path,"r");
	
	if(sf == NULL || gh == NULL)
		return;
		
	while(!feof(sf)){
		fscanf(sf,"%d,%d,%d,%d",&state,&last_installed,&last_attempted,&local_aru);
	}
	
	//fprintf(stderr,"%d,%d,%d,%d\n",state,last_installed,last_attempted,local_aru);
	
	while(!feof(gh)){
		//fprintf(stderr,"Starting Loop\n");
		char* line = (char*) malloc(sizeof(char)*20000);
		bzero((char*)line,20000);
		fscanf(gh,"%s\n",line);
		//fprintf(stderr,"LINE: %s\n",line);
		struct global_history *ghtmp = deserialize_gh(line);
		//fprintf(stderr,"Adding to List\n");
		list_add_tail(&(ghtmp->list),&(history.list));
	}
	
	fclose(sf);
	fclose(gh);
	
	//fprintf(stderr,"Restore Successful\n");
}